package com.kotlin.book.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.databinding.ItemClassScreeningBinding

class ClassScreeningItemAdapter(
    private var itemList: List<String>,
    private val callback: (Int?) -> Unit
) :
    RecyclerView.Adapter<ClassScreeningItemAdapter.ViewHolder>() {
    private var currentIndex: Int? = null

    class ViewHolder(itemBinding: ItemClassScreeningBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {
        val textView = itemBinding.text
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            ItemClassScreeningBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = itemList[position]
        holder.textView.text = item

        if (currentIndex == position) {
            holder.textView.background =
                ContextCompat.getDrawable(
                    holder.itemView.context,
                    R.drawable.class_screening_active_bg
                )
            holder.textView.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.primary_color
                )
            )
        } else {
            holder.textView.background =
                ContextCompat.getDrawable(holder.itemView.context, R.drawable.class_screening_bg)
            holder.textView.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.text_color_hint
                )
            )
        }

        holder.itemView.setOnClickListener {
            currentIndex = holder.adapterPosition
            callback(currentIndex)
            notifyDataSetChanged()
        }
    }

    fun setCurrentIndex(index: Int?) {
        currentIndex = index
        notifyDataSetChanged()
    }

}